package okhttp;

import okhttp3.*;
import okio.ByteString;
import java.util.concurrent.TimeUnit;

public class WebSocketDemo {

    public static void main(String[] args) {
        // 1. 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .pingInterval(10, TimeUnit.SECONDS) // 心跳检测（可选）
                .build();

        // 2. 定义 WebSocket 监听器
        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("WebSocket 连接已建立");
                // 连接成功后发送消息
                webSocket.send("Hello, Server!");
                webSocket.send(ByteString.encodeUtf8("Binary message")); // 发送二进制数据
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("收到文本消息: " + text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                System.out.println("收到二进制消息: " + bytes.hex());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("连接关闭中: " + code + " - " + reason);
                webSocket.close(1000, "正常关闭");
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                System.out.println("连接已关闭");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.err.println("连接失败: " + t.getMessage());
                t.printStackTrace();
            }
        };

        // 3. 创建 WebSocket 请求
        Request request = new Request.Builder()
                .url("ws://echo.websocket.org") // 测试用的公开 WebSocket 服务
                .build();

        // 4. 发起连接
        WebSocket webSocket = client.newWebSocket(request, listener);

        // 5. 模拟持续运行（实际应用中可能是 Android 或后台服务）
        try {
            Thread.sleep(5000); // 保持连接 5 秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 6. 主动关闭连接
            webSocket.close(1000, "用户主动关闭");
            client.dispatcher().executorService().shutdown(); // 清理资源
        }
    }
}
